package syn;

/**
 * @author mubei
 * @date 2021/11/20
 * @description  死锁  多个线程互相抱着别人的资源不放手
 */
public class DeadLock {

    public static void main(String[] args) {
        new Thread( new MakeUp(0, "ah")).start();
        new Thread( new MakeUp(1, "mv")).start();


    }
}


class Lipstick{

}

class Mirror{

}

class MakeUp implements Runnable{

    static Lipstick lipstick = new Lipstick();
    static Mirror mirror = new Mirror();

    int choice;
    String girlName;
    MakeUp(int choice, String girlName){
        this.choice = choice;
        this.girlName = girlName;
    }

    @Override
    public void run() {
        makeUp();
    }

    // 化妆的方法  互相持有对方的资源
    private void makeUp(){
        if(choice == 0){
            // 获得口红的锁
            synchronized(lipstick){
                System.out.println(this.girlName+"获得口红的锁");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (mirror){
                    System.out.println(this.girlName+"1秒钟后获得镜子的锁");
                }
            }
        }else{
            synchronized(mirror){
                System.out.println(this.girlName+"获得镜子的锁");
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lipstick){
                    System.out.println(this.girlName+"2秒钟后获得口红的锁");
                }
            }
        }
    }
}
